package web;

import ejb.ExCourseSession;
import ejb.UserSession;
import entity.ExCourse;
import entity.LogMessage;
import java.math.BigDecimal;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name = "manage")
@SessionScoped
public class OperationManagementBean {

    @EJB
    private ExCourseSession exCourseSession;
    @EJB
    private UserSession userSession;
    private LogMessage logMessage;
    private ExCourse course;
    private List<BigDecimal> values;
    private List<String> currencies;
    private String sellCurrency;
    private String buyCurrency;

    public OperationManagementBean() {
    }

    public LogMessage getMessage() {
        if (logMessage == null) {
            logMessage = new LogMessage();
        }
        return logMessage;
    }

    public List<LogMessage> getMessages() {
        return userSession.retrieve();
    }

    public void setMessage(String text) {
        logMessage.setMessage(text);
    }

    public void saveMessage() {
        BigDecimal purchased = new BigDecimal(logMessage.getMessage()).multiply(new BigDecimal(exCourseSession.getExchangeRate(sellCurrency, buyCurrency)));
        StringBuilder s = new StringBuilder();
        s.append("sold: ").append(logMessage.getMessage()).append(sellCurrency)
                .append(", purchased: ").append(purchased).append(buyCurrency);
        logMessage.setMessage(s.toString());
        userSession.persist(logMessage);
        
        sellCurrency = null;
        buyCurrency = null;
        logMessage = null;
    }

    public void setId(long id) {
        logMessage.setId(id);
    }

    public List<BigDecimal> getValues() {
        values = exCourseSession.getValues();
        return values;
    }

    public ExCourse getCourse() {
        if (course == null) {
            course = new ExCourse();
        }
        return course;
    }

    public List<ExCourse> getExchangeCourses() {
        return exCourseSession.retrieve();
    }

    public List<String> getCurrencies() {
        currencies = exCourseSession.getCurrency();
        return currencies;
    }

    public String getSellCurrency() {
        return sellCurrency;
    }

    public void setSellCurrency(String curr) {
        sellCurrency = curr;
    }

    public String getBuyCurrency() {
        return buyCurrency;
    }

    public void setBuyCurrency(String curr) {
        buyCurrency = curr;
    }
}
